{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "91c6a7ef",
   "metadata": {},
   "source": [
    "# Redis\n",
    "\n",
    ">[Redis (Remote Dictionary Server)](https://en.wikipedia.org/wiki/Redis) is an open-source in-memory storage, used as a distributed, in-memory key–value database, cache and message broker, with optional durability. Because it holds all data in memory and because of its design, `Redis` offers low-latency reads and writes, making it particularly suitable for use cases that require a cache. Redis is the most popular NoSQL database, and one of the most popular databases overall.\n",
    "\n",
    "This notebook goes over how to use `Redis` to store chat message history."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "897a4682-f9fc-488b-98f3-ae2acad84600",
   "metadata": {},
   "source": [
    "## Setup\n",
    "First we need to install dependencies, and start a redis instance using commands like: `redis-server`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cda8b56d-baf7-49a2-91a2-4d424a8519cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "pip install -U langchain-community redis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b11090e7-284b-4ed2-9790-ce0d35638717",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.chat_message_histories import RedisChatMessageHistory"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20b99474-75ea-422e-9809-fbdb9d103afc",
   "metadata": {},
   "source": [
    "## Store and Retrieve Messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d15e3302",
   "metadata": {},
   "outputs": [],
   "source": [
    "history = RedisChatMessageHistory(\"foo\", url=\"redis://localhost:6379\")\n",
    "\n",
    "history.add_user_message(\"hi!\")\n",
    "\n",
    "history.add_ai_message(\"whats up?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "64fc465e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[HumanMessage(content='hi!'), AIMessage(content='whats up?')]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "history.messages"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "465fdd8c-b093-4d19-a55a-30f3b646432b",
   "metadata": {},
   "source": [
    "## Using in the Chains"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94d65d2f-e9bb-4b47-a86d-dd6b1b5e8247",
   "metadata": {},
   "outputs": [],
   "source": [
    "pip install -U langchain-openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ace3e7b2-5e3e-4966-b549-04952a6a9a09",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Optional\n",
    "\n",
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "from langchain_core.runnables.history import RunnableWithMessageHistory\n",
    "from langchain_openai import ChatOpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5c1fba0d-d06a-4695-ba14-c42a3461ada1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='Your name is Bob, as you mentioned earlier. Is there anything specific you would like assistance with, Bob?')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", \"You're an assistant。\"),\n",
    "        MessagesPlaceholder(variable_name=\"history\"),\n",
    "        (\"human\", \"{question}\"),\n",
    "    ]\n",
    ")\n",
    "\n",
    "chain = prompt | ChatOpenAI()\n",
    "\n",
    "chain_with_history = RunnableWithMessageHistory(\n",
    "    chain,\n",
    "    lambda session_id: RedisChatMessageHistory(\n",
    "        session_id, url=\"redis://localhost:6379\"\n",
    "    ),\n",
    "    input_messages_key=\"question\",\n",
    "    history_messages_key=\"history\",\n",
    ")\n",
    "\n",
    "config = {\"configurable\": {\"session_id\": \"foo\"}}\n",
    "\n",
    "chain_with_history.invoke({\"question\": \"Hi! I'm bob\"}, config=config)\n",
    "\n",
    "chain_with_history.invoke({\"question\": \"Whats my name\"}, config=config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76ce3f6b-f4c7-4d27-8031-60f7dd756695",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
